package controller

import (
	"fmt"
	"gitee.com/youbeiwuhuan/gin-practice/gin-gorm2/global/consts"
	"gitee.com/youbeiwuhuan/gin-practice/gin-gorm2/internal/dao"
	"gitee.com/youbeiwuhuan/gin-practice/gin-gorm2/tools/render"
	"github.com/gin-gonic/gin/binding"
	"net/http"

	//auths "gitee.com/youbeiwuhuan/gin-practice/gin-simple-zap/internal/web/middleware/auths"
	"github.com/gin-gonic/gin"
)

type LoginForm struct {
	Username string `json:"username" validate:"required"`
	Password string `json:"password" validate:"required"`
}

type UserInfo struct {
	Age   uint8  `json:"age" validate:"gte=1,lte=130"`
	Name  string `json:"name" validate:"required"`
	Email string `json:"email" validate:"required,email0"`
}

func createUserGroup(rootRouter *gin.Engine) {
	userGroup := rootRouter.Group("/user" /* , auths.CheckTokenAuth() */)
	userGroup.GET("/userId", func(c *gin.Context) {
		var userDao = dao.GetDao("UserDao").(dao.IUserDao)

		fmt.Printf("----------%+v", userDao)

		// 获取登录用户id
		userId, exist := c.Get(consts.USER_ID)
		if exist {
			fmt.Printf("--------userId---%s \n", userId)

		} else {

		}

		render.OK(c, userId)

	})

	userGroup.POST("/addShouldBind", func(c *gin.Context) {
		var u UserInfo
		//  ShouldBindXXXX 会触发校验   ,
		if err := c.ShouldBindJSON(&u); err != nil {

			render.ReturnValidErr(c, err)
			return
		}
		render.OK(c, "")
	})

	userGroup.POST("/addBind", func(c *gin.Context) {
		// ShouldBindXXXX BindXXXX 会触发校验 但校验错误可以忽略
		var u UserInfo
		if err := c.BindJSON(&u); err != nil {
			fmt.Printf("------------------%d  %s  %s \n", u.Age, u.Name, u.Email)
			render.ReturnValidErr(c, err)
			return
		}
		// 这里可以再手动进行校验
		render.OK(c, "未触发校验")
	})

	userGroup.POST("/multiBind", func(c *gin.Context) {

		/*
			与 ShouldBind 的区别：
				ShouldBind 会消耗请求体，后续绑定会失败
				ShouldBindBodyWith 保存请求体，允许多次绑定
		*/
		// 第一个结构体绑定
		var login LoginForm
		if err := c.ShouldBindBodyWith(&login, binding.JSON); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// 第二个结构体绑定 - 使用相同的请求体
		var user UserInfo
		if err := c.ShouldBindBodyWith(&user, binding.JSON); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		// 处理绑定后的数据
		c.JSON(http.StatusOK, gin.H{
			"login": login,
			"user":  user,
		})

	})

}
